<template>
  <div
    class="page_body"
    v-loading.fullscreen.lock="loadingKey"
    :element-loading-text="loadingText"
  >
    <!-- 面包屑 -->
    <el-row>
      <el-col :span="24" class="page_box_top">
        <i class="el-icon-s-fold"></i>
        <el-breadcrumb separator="/" class="page_box_top_nav">
          <el-breadcrumb-item
            :to="{ name: 'MatchList' }"
            class="breadcrumb_active_item"
            >赛事名称管理</el-breadcrumb-item
          >
          <el-breadcrumb-item class="breadcrumb_active_item"
            ><span @click="matchDetail()" style="cursor: pointer">
              {{ matchtitle }}
            </span></el-breadcrumb-item
          >
          <el-breadcrumb-item>关联部门</el-breadcrumb-item>
        </el-breadcrumb>
      </el-col>
    </el-row>
    <el-row>
      <div class="department_manager_content">
        <!-- 按钮栏 -->
        <el-row>
          <el-col :span="24">
            <div class="department_manager_top">
              <el-button
                size="mini"
                type="primary"
                @click="addFn()"
                v-if="userType == 0"
                >添加</el-button
              >
              <el-input
                v-model="searchKey"
                placeholder="请输入关键词"
                size="mini"
                style="width: 200px; margin-left: 10px"
              ></el-input>
              <el-button
                type="primary"
                size="mini"
                style="margin-left: 5px"
                @click="searchFn()"
                >搜索</el-button
              >
            </div>
          </el-col>
        </el-row>
        <!-- 数据列表 -->
        <div
          v-if="
            departmentListData != undefined && departmentListData.length > 0
          "
        >
          <el-row>
            <el-col :span="24">
              <el-table
                :data="departmentListData"
                border
                size="mini"
                style="width: 100%"
              >
                <el-table-column
                  type="index"
                  label="序号"
                  width="50"
                  align="center"
                >
                </el-table-column>

                <el-table-column
                  prop="department_name"
                  label="部门"
                  align="center"
                  min-width="180"
                >
                </el-table-column>

                <el-table-column
                  prop="manager"
                  label="部门领导"
                  align="center"
                  width="120"
                >
                </el-table-column>

                <el-table-column
                  prop="assistant"
                  label="部门内勤"
                  align="center"
                  width="120"
                >
                </el-table-column>

                <el-table-column label="报名二维码" align="center" width="120">
                  <template slot-scope="scope">
                    <el-link
                      type="primary"
                      @click="getCodeFn(scope.$index, scope.row)"
                      >点击查看</el-link
                    >
                  </template>
                </el-table-column>

                <el-table-column
                  prop="created_at"
                  label="添加时间"
                  width="200"
                  align="center"
                ></el-table-column>

                <el-table-column label="操作" min-width="250" align="center">
                  <template slot-scope="scope">
                    <el-button
                      size="mini"
                      type="primary"
                      v-if="userType == 0"
                      @click="managerFn(scope.$index, scope.row)"
                      >成员管理</el-button
                    >

                    <el-button
                      size="mini"
                      type="primary"
                      @click="companyListFn(scope.$index, scope.row)"
                      >公司管理</el-button
                    >

                    <el-button
                      size="mini"
                      type="primary"
                      @click="uploadListFn(scope.$index, scope.row)"
                      >导入名单</el-button
                    >

                    <el-button
                      size="mini"
                      type="danger"
                      v-if="userType == 0"
                      @click="deleteFn(scope.$index, scope.row)"
                      >删除</el-button
                    >
                  </template>
                </el-table-column>
              </el-table>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <div class="department_manager_pagination">
                <el-pagination
                  @size-change="listSizeChange"
                  @current-change="listCurrentChange"
                  :current-page="currentPage"
                  :page-sizes="pageSizes"
                  :page-size="pageSize"
                  layout="total, sizes, prev, pager, next, jumper"
                  :total="total"
                >
                </el-pagination>
              </div>
            </el-col>
          </el-row>
        </div>
        <el-row v-else>
          <el-empty description="暂无数据"></el-empty>
        </el-row>
        <!-- 弹窗 -->
        <el-dialog
          :title="dialogTitle"
          :visible.sync="dialogVisible"
          :close-on-click-modal="false"
          width="600px"
        >
          <el-form
            ref="dialogDetailForm"
            :model="detailFormData"
            :rules="detailFormRules"
            v-if="dialogBtnKey == 1 || dialogBtnKey == 2"
          >
            <el-form-item
              label="选择部门"
              prop="departmentSelect"
              :label-width="formLabelWidth"
            >
              <el-select
                size="small"
                v-model="detailFormData.departmentSelect"
                multiple
                placeholder="请选择"
              >
                <el-option
                  v-for="item in departmentSelectList"
                  :key="item.id"
                  :label="item.department_name"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-form>
          <div class="manager_list_box" v-if="dialogBtnKey == 3">
            <div class="manager_list_item">
              <div class="manager_list_item_title">部门领导:</div>
              <el-tag
                v-for="item in managerData.leaderList"
                :key="item.index"
                style="margin-right: 10px; margin-bottom: 10px"
                closable
                @close="removeUserFn(item.id)"
                >{{ item.username }}</el-tag
              >
              <div class="none_tips" v-if="managerData.leaderList.length == 0">
                暂无
              </div>
            </div>
            <div class="manager_list_item">
              <div class="manager_list_item_title">部门内勤:</div>
              <el-tag
                v-for="item in managerData.assistantList"
                :key="item.index"
                style="margin-right: 10px; margin-bottom: 10px"
                closable
                @close="removeUserFn(item.id)"
                >{{ item.username }}</el-tag
              >
              <div
                class="none_tips"
                v-if="managerData.assistantList.length == 0"
              >
                暂无
              </div>
            </div>
            <div class="manager_list_item_title" style="margin-bottom: 10px">
              添加成员:
            </div>
            <div class="manager_list_item">
              <el-form
                ref="addUserForm"
                :model="addUserData"
                :rules="addUserRules"
                style="display: flex"
              >
                <el-form-item
                  label="负责人"
                  prop="addUserId"
                  :label-width="addUserIdLabelWidth"
                  style="margin-bottom: 10px"
                >
                  <el-select
                    size="small"
                    v-model="addUserData.addUserId"
                    filterable
                    clearable
                    remote
                    placeholder="请输入名称或手机号"
                    :remote-method="remoteMethod"
                    :loading="selectLoading"
                    style="width: 180px; margin-right: 10px"
                  >
                    <el-option
                      v-for="item in userListData"
                      :key="item.id"
                      :label="item.username"
                      :value="item.id"
                    >
                    </el-option>
                  </el-select>
                </el-form-item>

                <el-form-item
                  label="职务"
                  prop="addRole"
                  label-width="60px"
                  style="margin-bottom: 10px"
                >
                  <el-select
                    size="small"
                    clearable
                    v-model="addUserData.addRole"
                    placeholder="请选择"
                    style="width: 100px; margin-right: 10px"
                  >
                    <el-option
                      v-for="item in roleList"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    >
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item style="margin-bottom: 10px">
                  <el-button
                    size="small"
                    type="primary"
                    v-if="userType == 0"
                    @click="addUserFn()"
                    >添加</el-button
                  >
                </el-form-item>
              </el-form>
            </div>
          </div>
          <span slot="footer" class="dialog-footer">
            <el-button
              v-if="dialogBtnKey != 3"
              size="small"
              @click="dialogclose()"
              >取 消</el-button
            >
            <el-button
              size="small"
              v-if="(dialogBtnKey == 1 || dialogBtnKey == 2) && userType == 0"
              type="primary"
              @click="dialogDetailFormSubmit()"
              >确 定</el-button
            >
            <el-button
              size="small"
              v-if="dialogBtnKey == 3"
              @click="dialogclose()"
              >关 闭</el-button
            >
          </span>
        </el-dialog>

        <!-- 二维码弹窗 -->
        <el-dialog
          title="报名二维码"
          :visible.sync="codeDalogVisible"
          :close-on-click-modal="false"
          width="400px"
        >
          <div ref="qrCode_box" class="card_data_body_qrcode"></div>
          <div class="qrCode_link">链接: {{ qrcodeUrl }}</div>
          <span slot="footer" class="dialog-footer">
            <el-button size="small" type="primary" @click="copy(qrcodeUrl)"
              >复制链接</el-button
            >
            <el-button size="small" @click="codeDialogclose()">关 闭</el-button>
          </span>
        </el-dialog>

        <!-- 导入名单弹窗 -->
        <el-dialog
          title="导入名单"
          :visible.sync="uploadDalogVisible"
          :close-on-click-modal="false"
          width="400px"
        >
          <el-upload
            ref="uploadListRef"
            class="upload-demo"
            :action="actionUrl"
            :headers="headers"
            :data="uploadFileData"
            :name="fileName"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
            :file-list="fileList"
            multiple
          >
            <el-button slot="trigger" size="small" type="primary"
              >上传文件</el-button
            >
            <div slot="tip" class="el-upload__tip">
              选择名单xlsx文件或图片png/jpg文件上传
            </div>
          </el-upload>

          <span slot="footer" class="dialog-footer">
            <el-button
              size="small"
              type="primary"
              @click="downloadTemplate(qrcodeUrl)"
              >下载模板</el-button
            >
            <el-button size="small" @click="uploadDialogclose()"
              >关 闭</el-button
            >
          </span>
        </el-dialog>
      </div>
    </el-row>
  </div>
</template>
<style src="../../assets/css/match/matchBindDepartment.css" scoped></style>

<script>
import QRCode from "qrcodejs2";

export default {
  name: "MatchBindDepartment",
  components: {},
  data() {
    return {
      userType: this.$store.state.loginUserType == "ADMINLOGINUSERCH" ? 0 : 1, // 用户类型;1. 普通; 0. 超级;
      baseAPIUrl: this.$store.state.baseAPIUrl,
      matchId: "", // 赛事名称id
      matchtitle: "", // 赛事名称名称
      departmentListData: [], // 数据列表
      currentPage: 1, // 当前页
      pageSizes: [10, 20, 50, 100], // 可选页容量
      pageSize: 10, // 当前页容量
      total: 0, // 总条数
      searchKey: "", // 搜索关键词
      loadingKey: false,
      loadingText: "",
      dialogTitle: "", // 弹窗标题
      dialogBtnKey: "", // 弹窗确认按钮控制; 1. 新增部门确认;3. 管理部门确认
      dialogVisible: false, // 弹窗显示
      codeDalogVisible: false, // 二维码弹窗显示
      detailFormData: {
        departmentSelect: [],
      }, // 部门弹窗数据
      detailFormRules: {
        departmentSelect: [
          { required: true, message: "请选择部门", trigger: "change" },
        ],
      },
      formLabelWidth: "90px",
      selectLoading: false,
      userListData: [], // 用户列表数据
      managerData: {
        id: "",
        leaderList: [],
        assistantList: [],
      },
      addUserData: {
        addUserId: "",
        addRole: null,
      },
      addUserIdLabelWidth: "70px",
      addUserRules: {
        addUserId: [
          { required: true, message: "请选择负责人", trigger: "change" },
        ],
        addRole: [{ required: true, message: "请选择职务", trigger: "change" }],
      },
      roleList: [
        {
          value: 1,
          label: "部门领导",
        },
        {
          value: 2,
          label: "部门内勤",
        },
      ],
      departmentSelectList: [],
      qrcodeUrl: "", // 二维码链接
      uploadDalogVisible: false, // 导入文件弹窗显示
      actionUrl: "",
      headers: {
        Authorization: this.$store.state.loginToken,
      }, // 导入headers
      uploadData: {
        event_id: "",
        department_id: "",
      }, // 导入参数
      uploadFileData: {}, // 导入组件参数
      fileName: "",
      fileList: [],

      department_id: "", //下载模板的部门id
    };
  },
  created: function () {
    let matchId = this.$route.query.id;
    if (matchId != undefined && matchId != "") {
      this.matchId = matchId;
    }

    this.getListDataFn();
    this.getDepartmentList();
    this.getUserListDataFn();
  },
  methods: {
    // 获取列表数据
    getListDataFn: function () {
      let that = this;
      let url = "/admin/eventdepartment/index";
      let data = {
        event_id: this.matchId,
        page: this.currentPage,
        perPage: this.pageSize,
        keywords: this.searchKey,
      };
      that.loadingText = "加载中...";
      that.loadingKey = true;
      this.axios
        .post(url, data)
        .then((response) => {
          that.loadingKey = false;
          if (response.code == 0) {
            that.matchtitle = response.event.title;
            that.departmentListData = response.list;
            that.total = response.total_count;
          } else {
            that.$message.error(response.msg);
          }
        })
        .catch(function (error) {
          that.loadingKey = false;
          console.log(error);
        });
    },
    // 获取部门数据
    getDepartmentList: function () {
      let that = this;
      let url = "/admin/department/index";
      let data = {};
      that.loadingText = "加载中...";
      that.loadingKey = true;
      this.axios
        .post(url, data)
        .then((response) => {
          that.loadingKey = false;
          if (response.code == 0) {
            that.departmentSelectList = response.list;
          } else {
            that.$message.error(response.msg);
          }
        })
        .catch(function (error) {
          that.loadingKey = false;
          console.log(error);
        });
    },
    // 获取用户列表数据
    getUserListDataFn: function (query) {
      let that = this;
      let url = "/admin/adminusers/index";
      let data = {
        keywords: "",
      };
      if (query) {
        data = {
          keywords: query,
        };
      }
      this.axios
        .post(url, data)
        .then((response) => {
          that.selectLoading = false;
          if (response.code == 0) {
            that.userListData = response.list;
          } else {
            that.$message.error(response.msg);
          }
        })
        .catch(function (error) {
          that.selectLoading = false;
          console.log(error);
        });
    },
    // 获取部门详情
    getDetailFn: function (id) {
      let that = this;
      let url = "/admin/eventdepartment/show";
      let data = {
        id: id,
      };
      that.loadingText = "加载中...";
      that.loadingKey = true;
      this.axios
        .post(url, data)
        .then((response) => {
          that.loadingKey = false;
          if (response.code == 0) {
            that.managerData = {
              id: id,
              leaderList: response.manager,
              assistantList: response.assistant,
            };
            that.addUserData = {
              addUserId: "",
              addRole: null,
            };
            that.$nextTick(function () {
              that.dialogVisible = true;
              that.$refs.addUserForm.clearValidate();
            });
          } else {
            that.$message.error(response.msg);
          }
        })
        .catch(function (error) {
          that.loadingKey = false;
          console.log(error);
        });
    },
    // 新增部门
    addFn: function () {
      let that = this;
      this.dialogTitle = "新增部门";
      this.dialogBtnKey = 1;
      this.detailFormData = {
        departmentSelect: [],
      };
      that.dialogVisible = true;
      this.$nextTick(function () {
        that.$refs.dialogDetailForm.clearValidate();
      });
    },
    // 新增部门保存按钮
    dialogDetailFormSubmit: function () {
      let that = this;
      let url = "/admin/event/addDepartmentMany";
      let data = {
        event_id: this.matchId,
        department_ids: this.detailFormData.departmentSelect.join(","),
      };
      this.$refs.dialogDetailForm.validate((valid) => {
        if (!valid) {
          return false;
        } else {
          that
            .$confirm("确认提交?", "提示", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
            })
            .then(() => {
              that.loadingText = "处理中...";
              that.loadingKey = true;
              that.axios
                .post(url, data)
                .then((response) => {
                  that.loadingKey = false;
                  if (response.code == 0) {
                    that.$message.success("新增成功");
                    that.dialogclose();
                    that.getListDataFn();
                  } else {
                    that.$message.error(response.msg);
                  }
                })
                .catch(function (error) {
                  that.loadingKey = false;
                  console.log(error);
                });
            })
            .catch(() => {});
        }
      });
    },

    // 管理部门
    managerFn: function (index, row) {
      this.dialogTitle = "成员管理";
      this.dialogBtnKey = 3;
      this.$nextTick(function () {
        this.getDetailFn(row.id);
      });
    },

    // 关闭弹窗
    dialogclose: function () {
      this.dialogVisible = false;
      if (this.dialogBtnKey == 3) {
        this.getListDataFn();
      }
    },

    // 关闭二维码弹窗
    codeDialogclose: function () {
      this.codeDalogVisible = false;
    },

    // 关闭导入弹窗
    uploadDialogclose: function () {
      this.uploadDalogVisible = false;
    },

    // 导入名单
    uploadListFn: function (index, row) {
      let that = this;

      let department_id = row.department_id;
      this.department_id = row.department_id;
      console.log(department_id, row, this.department_id);
      this.uploadData = {
        event_id: this.matchId,
        department_id: department_id,
      };
      this.uploadDalogVisible = true;
      this.$nextTick(() => {
        that.$refs.uploadListRef.clearFiles();
      });
    },

    // 公司管理
    companyListFn: function (index, row) {
      console.log(row);
      this.$router.push({
        name: "CompanyManager",
        query: {
          id: row.id,
        },
      });
    },

    // 下载模板
    downloadTemplate: function () {
      let that = this;
      let url = "/excel/exportEventTemplateTwo";
      let data = {
        event_id: this.matchId,
        department_id: this.department_id,
      };

      that.loadingText = "处理中...";
      that.loadingKey = true;
      that.axios
        .post(url, data)
        //  { responseType: "blob" }
        .then((response) => {
          that.loadingKey = false;
          if (response.code == 1) {
            that.$message.error(response.msg);
          } else {
            let blob = new Blob([response], {
              type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8",
            });
            const link = document.createElement("a");
            // link.href = URL.createObjectURL(blob);
            // link.download = "event_import.xlsx";
            // document.body.appendChild(link);
            link.href = response.file;
            link.click();
            // window.URL.revokeObjectURL(link.href);
            // document.body.removeChild(link);
          }
        })
        .catch(function (error) {
          that.loadingKey = false;
          console.log(error);
        });
    },

    // 上传成功钩子
    handleAvatarSuccess: function (res) {
      if (res.code == 1) {
        this.$message.error(res.msg);
      } else {
        this.$message.success("导入成功");
      }
    },
    // 上传前钩子
    beforeAvatarUpload: function (file) {
      let that = this;
      let type = file.name.indexOf(".xlsx");
      const isJPG = file.type === "image/jpeg";
      const isPNG = file.type === "image/png";
      const isLt2M = file.size / 1024 / 1024 < 3;

      if (type == -1 && !isJPG && !isPNG) {
        this.$message.error("上传xlsx/jpg/png文件");
        return false;
      }
      if (isJPG || isPNG) {
        if (!isLt2M) {
          this.$message.error("上传图片大小不能超过 3MB!");
          resolve(false);
        }
      }

      return new Promise((resolve, reject) => {
        if (type != -1) {
          let dataObj = JSON.parse(JSON.stringify(this.uploadData));
          this.$set(
            that,
            "actionUrl",
            this.$store.state.baseAPIUrl + "/excel/importApply"
          );
          this.$set(that, "uploadFileData", dataObj);
          this.$set(that, "fileName", "excelfile");
          this.$nextTick(() => {
            resolve(true);
          });
        } else {
          let obj = {
            event_id: this.matchId,
          };
          this.$set(
            that,
            "actionUrl",
            this.$store.state.baseAPIUrl + "/upload/uploadPhotoFile"
          );
          this.$set(that, "uploadFileData", obj);
          this.$set(that, "fileName", "file");
          this.$nextTick(() => {
            resolve(true);
          });
        }
      });
    },

    // 复制文本
    copy: function (data) {
      let OrderNumber = data;
      // 创建一个input 元素
      let newInput = document.createElement("input");
      newInput.value = OrderNumber;
      document.body.appendChild(newInput);
      newInput.select();
      document.execCommand("Copy");
      newInput.remove();
      that.$message.success("复制成功");
    },
    // 报名二维码
    getCodeFn: function (index, row) {
      let that = this;
      this.codeDalogVisible = true;
      this.$nextTick(() => {
        that.$refs.qrCode_box.innerHTML = "";
        that.qrcodeUrl = that.$store.state.baseUrl + "login?mark=" + row.mark;
        that.createQRCodeFn(row.mark).then(() => {});
      });
    },
    // 生成二维码
    createQRCodeFn: function (mark) {
      let that = this;
      return new Promise(function (resolve) {
        setTimeout(function () {
          let text = that.$store.state.baseUrl + "login?mark=" + mark;
          let qrcodejs2 = new QRCode(that.$refs.qrCode_box, {
            text: JSON.stringify(text), //二维码内容
            colorDark: "#000000",
            colorLight: "#ffffff",
          });
          resolve(qrcodejs2);
        }, 1000);
      });
    },
    // 删除
    deleteFn: function (index, row) {
      let that = this;
      this.$confirm("确认删除该部门?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
      })
        .then(() => {
          let url = "/admin/eventdepartment/destroy";
          let data = {
            id: row.id,
          };
          that.loadingText = "处理中...";
          that.loadingKey = true;
          that.axios
            .post(url, data)
            .then((response) => {
              that.loadingKey = false;
              if (response.code == 0) {
                that.$message.success("删除成功");
                let next = that.currentPage - 1;
                if (that.departmentListData.length == 1) {
                  that.currentPage = next >= 1 ? next : 1;
                }
                that.getListDataFn();
              } else {
                that.$message.error(response.msg);
              }
            })
            .catch(function (error) {
              that.loadingKey = false;
              console.log(error);
            });
        })
        .catch(() => {});
    },
    // 页容量改变
    listSizeChange: function (val) {
      this.currentPage = 1;
      this.pageSize = val;
      this.getListDataFn();
    },
    // 当前页改变
    listCurrentChange: function (val) {
      this.currentPage = val;
      this.getListDataFn();
    },
    // 搜索按钮
    searchFn: function () {
      this.currentPage = 1;
      this.getListDataFn();
    },
    // 成员选择搜索
    remoteMethod: function (query) {
      if (query !== "") {
        this.selectLoading = true;
        this.getUserListDataFn(query);
      } else {
        this.selectLoading = true;
        this.getUserListDataFn();
      }
    },
    // 添加成员
    addUserFn: function () {
      let that = this;
      let url = "/admin/eventdepartment/addManager";
      let data = {
        event_department_id: this.managerData.id,
        admin_userid: this.addUserData.addUserId,
        role: this.addUserData.addRole,
      };
      this.$refs.addUserForm.validate((valid) => {
        if (!valid) {
          return false;
        } else {
          that.loadingText = "处理中...";
          that.loadingKey = true;
          that.axios
            .post(url, data)
            .then((response) => {
              that.loadingKey = false;
              if (response.code == 0) {
                that.$message.success("添加成功");
                that.getDetailFn(that.managerData.id);
              } else {
                that.$message.error(response.msg);
              }
            })
            .catch(function (error) {
              that.loadingKey = false;
              console.log(error);
            });
        }
      });
    },
    // 移除成员
    removeUserFn: function (value) {
      let that = this;
      this.$confirm("确认移除?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
      })
        .then(() => {
          let url = "/admin/eventdepartment/deleteManager";
          let data = {
            id: value,
          };
          that.loadingText = "处理中...";
          that.loadingKey = true;
          that.axios
            .post(url, data)
            .then((response) => {
              that.loadingKey = false;
              if (response.code == 0) {
                that.$message.success("移除成功");
                that.getDetailFn(that.managerData.id);
              } else {
                that.$message.error(response.msg);
              }
            })
            .catch(function (error) {
              that.loadingKey = false;
              console.log(error);
            });
        })
        .catch(() => {});
    },
    // 活动详情
    matchDetail: function () {
      const routeUrl = this.$router.resolve({
        name: "MatchFrom",
      });
      window.open(routeUrl.href + "?id=" + this.matchId + "&key=3", "_blank");
    },
  },
};
</script>
